/*** Document is ready */ // Global vars var wohicpopup = null; // keep track of popup's status var elements; document.addEventListener("DOMContentLoaded", function () { elements = new WOHICPlugin(); elements.loadStylesResources(); //elements.loadScriptsResources(); const popupBtns = document.querySelectorAll("[data-mode=popup] .btn"); if (popupBtns[0]) { popupBtns.forEach(function (popupBtn) { event.preventDefault(); elements.popupA11y(popupBtn); }); } window.addEventListener("click", function (event) { // Enrollment const modals = document.querySelectorAll("[data-wohic=enrollment] .btn"); if (event.target == modals[0]) { modals.forEach(function (modal) { event.preventDefault(); //elements.signupModal(event.target); elements.signup(event.target); }); } //Enrollment Modal Close Btn const modalsClosebtn = document.querySelectorAll("[data-wohic=enrollment] .modal-close"); if (event.target == modalsClosebtn[0]) { modalsClosebtn.forEach(function (closebtn) { event.preventDefault(); elements.signupModalClose(event.target); }); } //Enrollment submit const enrollFormSubmit = document.querySelectorAll(".woh-enrollment-form .form-submit"); if (event.target == enrollFormSubmit[0]) { enrollFormSubmit.forEach(function (elem) { event.preventDefault(); elements.onSignupFormSubmit(event.target); }); } // Sign-in link from Enrollment form //const enrollmentSigninLinks = document.querySelectorAll("[data-wohic=enrollment] [data-wohic=signin]"); //if (event.target == enrollmentSigninLinks[0]) { // enrollmentSigninLinks.forEach(function () { // event.preventDefault(); // elements.signin(event.target); // }); //} // Sign-in button const signinLinks = document.querySelectorAll("[data-wohic=signin] .btn"); if (event.target == signinLinks[0]) { signinLinks.forEach(function () { event.preventDefault(); elements.signin(event.target); }); } // Logout button const logoutBtns = document.querySelectorAll("[data-wohic=logout] .btn"); if (event.target == logoutBtns[0]) { logoutBtns.forEach(function () { event.preventDefault(); elements.logout(event.target); }); } }); }); /*** Document is loaded */ window.addEventListener("load", function (event) { const form = $(".woh-enrollment-form"); elements = new WOHICPlugin(); Array.from(form).forEach(element => { const statedd = element.querySelector(".state_dd"); const countrydd = element.querySelector(".country_dd"); // Show and hide state dd $(countrydd).chosen().on('change', (e, country) => { $(statedd).chosen().on('change', () => { }); $(statedd).empty() $(statedd).append(``); const selectedCountry = $(countrydd).val().toLowerCase() const states = $(statedd).data('list').filter(state => state.Country.toLowerCase() == selectedCountry); if (states && states.length) { $(statedd).attr('disabled', false); $(statedd).removeClass('hidden'); $(statedd).parent().siblings('.form-label').removeClass('hidden'); states.forEach((state) => { $(statedd).append(``); }); } else { $(statedd).attr('disabled', true); $(statedd).addClass('hidden'); $(statedd).parent().siblings('.form-label').addClass('hidden'); } $(statedd).trigger('chosen:updated'); elements.enableRegisterButton(e.target); }); }); $(document).on("keydown", function (e) { if (e.keyCode == 9) { const chosenContainer = $(e.target).parents(".chosen-container"); if (chosenContainer && chosenContainer.length > 0) { const stateField = chosenContainer.siblings(".state_dd"); const countryField = chosenContainer.siblings(".country_dd"); const form = e.target.closest(".woh-enrollment-form"); const country = form.querySelector(".country_dd"); const state = form.querySelector(".state_dd"); if (countryField && countryField.length > 0) { elements.enableRegisterButton(e.target); elements.validateCountry(country, true); } else if (stateField && stateField.length > 0) { elements.enableRegisterButton(e.target); elements.validateState(state, true); } } } }); }); /*** -------------------------------------------------- */ (function () { /*** Register plugin in window object */ this.WOHICPlugin = function () { let defaults = {}; // container to store i.E. the DOM elements to which the plugin is applied this.elements = []; this.settings = (arguments[0] && typeof arguments[0] === 'object') ? extendDefaults(defaults, arguments[0]) : defaults; // start the plugin this.init(); } /*** Public Methods */ WOHICPlugin.prototype.init = function () { console.log('Init WOHIC plugin.'); build.call(this); } WOHICPlugin.prototype.update = function (element) { console.log('Update plugin.'); } WOHICPlugin.prototype.signupModal = function (element) { signupModal(element); } WOHICPlugin.prototype.signup = function (element) { signup(element); } WOHICPlugin.prototype.onSignupFormSubmit = function (element) { onSignupFormSubmit(element); } WOHICPlugin.prototype.signin = function (element) { signin(element); } WOHICPlugin.prototype.loadStylesResources = function () { loadStylesResources(); } WOHICPlugin.prototype.enableRegisterButton = function (element) { enableRegisterButton(element); } WOHICPlugin.prototype.validateCountry = function (element, isSetError) { validateCountry(element, isSetError); } WOHICPlugin.prototype.validateState = function (element, isSetError) { validateState(element, isSetError); } //WOHICPlugin.prototype.loadScriptsResources = function () { // loadScriptsResources(); //} WOHICPlugin.prototype.popupA11y = function (element) { popupA11y(element); } WOHICPlugin.prototype.closePopup = function (element) { closePopup(); } WOHICPlugin.prototype.signupModalClose = function (element) { signupModalClose(element); } WOHICPlugin.prototype.logout = function (element) { logout(element); } WOHICPlugin.prototype.closePopup = function (element) { closePopup(element); } /*** Private Methods */ // called by init() to set up everything in DOM, events, etc. function build(element) { console.log('Build plugin.'); } // used when registering the plugin in the window object. function extendDefaults(defaults, properties) { Object.keys(properties).forEach(property => { if (properties.hasOwnProperty(property)) { defaults[property] = properties[property]; } }); return defaults; } function getReturnUrl(url) { const idx = url.toLowerCase().indexOf('returnurl'); return idx > 0 ? url.substring(idx + 10) : url; } function signup(element) { try { var dataRedirectUriContainer = element.closest("[data-wohic]"); // Check Signin version (popup/redirect) var isPopupEnabled = dataRedirectUriContainer.dataset.mode; var redirectUri = ""; // Get enrollment form reference var enrollmentPage = ""; var enrollmentPage = dataRedirectUriContainer.dataset.uri; const eventJson = JSON.stringify({ "event": "Web_Join", }); if (!(enrollmentPage === null || enrollmentPage === undefined) && enrollmentPage != "") { redirectUri = enrollmentPage; if (isPopupEnabled === null || isPopupEnabled === undefined || isPopupEnabled != "popup") { var url = new URL(redirectUri); if (!url.searchParams.has("returnURL")) { url.searchParams.append("returnURL", getReturnUrl(window.location.href)); redirectUri = url.toString(); } else { redirectUri = url.toString(); } pushGtmEventAndRedirect(eventJson, redirectUri); } else { // Setup popup let height = 720; let width = 520; const windowFeatures = "top=" + (screen.height - height) / 2 + ",left=" + (screen.width - width) / 2 + ",resizable=yes,width=" + width + ",height=" + height; wohicpopup = window.open( redirectUri, "wohicpopup", windowFeatures ); wohicpopup.is_popup = true; window.gtmService.pushGtmEvent(eventJson); } } //loadScriptEnrollmentForm(); if (!wohicpopup) { // TODO // The window wasn't allowed to open // This is likely caused by built-in popup blockers. } } catch (e) { console.error(e); } } function onSignupFormSubmit(formSubmitBtn) { try { //Get user form data var formData = getEnrollFormData(formSubmitBtn); if (!(JSON.stringify(formData) === '{}')) { submitEnrollment(formData); } } catch (e) { console.error(e); } } function signin(element) { var dataRedirectUriContainer = element.closest("[data-wohic]"); var returnURL = dataRedirectUriContainer.dataset.uri; // Check Signin version (popup/redirect) var isPopupEnabled = dataRedirectUriContainer.dataset.mode; const eventJson = JSON.stringify({ "event": "Web_login", }); if (!(isPopupEnabled === null || isPopupEnabled === undefined) && isPopupEnabled == "popup") { if (wohicpopup != null && wohicpopup.closed) { wohicpopup = null; } // If popup doesnt exist then open a new one if (wohicpopup == null) { //A11y var signinBtn = dataRedirectUriContainer.querySelector(".btn"); signinBtn.setAttribute("aria-label", "popup open"); //A11y end let height = 720; let width = 520; const windowFeatures = "top=" + (screen.height - height) / 2 + ",left=" + (screen.width - width) / 2 + ",resizable=yes,width=" + width + ",height=" + height; var popupURL = "/ExternalLogin/WOHLogin?popup=true"; if (!(returnURL === null || returnURL === undefined) && returnURL != "") popupURL = popupURL & "&returnURL=" + getReturnUrl(window.location.href); wohicpopup = window.open( popupURL, "wohicpopup", windowFeatures ); } else { wohicpopup = wohicpopup; } if (wohicpopup != null) wohicpopup.focus(); if (!wohicpopup) { // TODO // The window wasn't allowed to open // This is likely caused by built-in popup blockers. } //closePopup(element, wohicpopup); //wohicpopup.onbeforeunload = closePopup(wohicpopup); window.gtmService.pushGtmEvent(eventJson); } else if (window.is_popup) { var targetUrl = "/ExternalLogin/WOHLogin?popup=true&returnURL=" + getReturnUrl(window.location.href); pushGtmEventAndRedirect(eventJson, targetUrl); } else { var targetUrl = "/ExternalLogin/WOHLogin?popup=false&returnURL=" + getReturnUrl(window.location.href); pushGtmEventAndRedirect(eventJson, targetUrl); } } function pushGtmEventAndRedirect(eventJson, targetUrl) { try { if (window.gtmService.gtmEnabled() && window.gtmService.gtmLoaded()) { window.gtmService.pushGtmEventWithCallback(eventJson, function () { window.location.href = targetUrl; }, 2000); } else { window.location.href = targetUrl; } } catch (e) { window.location.href = targetUrl; } } function logout(element) { var logoutEndpoint = ""; var logoutContainer = element.closest("[data-wohic]"); // Get logoutEndpoint from the view var customLogoutEndpoint = logoutContainer.dataset.uri; if (!(customLogoutEndpoint === null || customLogoutEndpoint === undefined) && customLogoutEndpoint != "") { logoutEndpoint = customLogoutEndpoint; } else { // If not setup, then get default logoutEndpoint logoutEndpoint = `/Loyalty/Logout?returnURL=${getReturnUrl(window.location.href)}`; } window.location.replace(logoutEndpoint); } function closePopup(wohicpopup) { var formsContainer = document.querySelectorAll("[data-wohic]"); formsContainer.forEach(function (form) { var signinBtn = form.querySelector(".btn"); signinBtn.removeAttribute("aria-haspopup", "true"); signinBtn.setAttribute("aria-label", "popup close"); }); } function getEnrollmentForm(modal) { const token = $("input[name='__RequestVerificationToken']").val(); return new Promise(async function (resolve, reject) { // do async thing const res = await fetch("/modules/Trisept.Epi.Addons.WOH/Enrollment/GetView", { method: "POST", headers: { "Content-Type": "application/json;charset=utf-8", "Accept": "application/json", "RequestVerificationToken": token }, }).then(function (response) { // The API call was successful! if (response.ok) { return response.json(); } else { return Promise.reject(response); } }).then(function (data) { // This is the JSON from our response console.log(data); modal.innerHTML = data; return data; }).catch(function (err) { // There was an error console.warn("Something went wrong.", err); }); // resolve resolve(res) }); } //Validation on focus and onchange $('input[type="email"]').on("blur focusout keyup", function (e) { if (e.type !== 'keyup' || e.keyCode !== 9) { if ($(e.target).parents(".enrollmenttemplate-page") && $(e.target).parents(".enrollmenttemplate-page").length > 0) { validateEmail(event.target, true); enableRegisterButton(event.target); } } }); $('input[name="firstName"]').on("blur focusout keyup", function (e) { if (e.type !== 'keyup' || e.keyCode !== 9) { if ($(e.target).parents(".enrollmenttemplate-page") && $(e.target).parents(".enrollmenttemplate-page").length > 0) { validateName(event.target, true); enableRegisterButton(event.target); } } }); $('input[name="lastName"]').on("blur focusout keyup", function (e) { if (e.type !== 'keyup' || e.keyCode !== 9) { if ($(e.target).parents(".enrollmenttemplate-page") && $(e.target).parents(".enrollmenttemplate-page").length > 0) { validateName(event.target, true); enableRegisterButton(event.target); } } }); $('.country_dd').on("chosen:showing_dropdown", function (e) { if ($(e.target).parents(".enrollmenttemplate-page") && $(e.target).parents(".enrollmenttemplate-page").length > 0) { validateCountry(e.target, true); enableRegisterButton(e.target); } }); $('.country_dd').on("chosen:hiding_dropdown", function (e) { if ($(e.target).parents(".enrollmenttemplate-page") && $(e.target).parents(".enrollmenttemplate-page").length > 0) { validateCountry(e.target, true); enableRegisterButton(e.target); } }); $('.state_dd').on("chosen:showing_dropdown", function (e) { if ($(e.target).parents(".enrollmenttemplate-page") && $(e.target).parents(".enrollmenttemplate-page").length > 0) { validateState(e.target, true); enableRegisterButton(e.target); } }); $('.state_dd').on("chosen:hiding_dropdown", function (e) { if ($(e.target).parents(".enrollmenttemplate-page") && $(e.target).parents(".enrollmenttemplate-page").length > 0) { validateState(e.target, true); enableRegisterButton(e.target); } }); function enableRegisterButton(inputElement) { const form = inputElement.closest(".woh-enrollment-form"); const email = form.querySelector("[name=email]"); const firstName = form.querySelector("[name=firstName]"); const lastName = form.querySelector("[name=lastName]"); const country = form.querySelector(".country_dd"); const state = form.querySelector(".state_dd"); const registerBtn = $(form).find('.submit-signin-btn-container button'); var isEmailValid = validateEmail(email, false); var isFirstNameValid = validateName(firstName, false); var isLastNameValid = validateName(lastName, false); var isCountryValid = validateCountry(country, false); var isStateValid = $(state).hasClass("hidden") ? true : validateState(state, false); if (isEmailValid && isFirstNameValid && isLastNameValid && isCountryValid && isStateValid) { $(registerBtn).removeClass('disabled'); $(registerBtn).removeAttr('disabled'); } else { $(registerBtn).addClass('disabled'); $(registerBtn).attr('disabled', true); } } function setError(inputElement, isSetError) { if (isSetError) { $(inputElement).parents('.form-element').addClass('error'); const errorText = inputElement.dataset.error; const error = document.createElement('span'); error.classList.add('error'); error.innerHTML = errorText; inputElement.after(error); } } function getEnrollFormData(formSubmitBtn) { try { const form = formSubmitBtn.closest(".woh-enrollment-form"); const email = form.querySelector("[name=email]"); const firstName = form.querySelector("[name=firstName]"); const lastName = form.querySelector("[name=lastName]"); const country = form.querySelector(".country_dd"); const state = form.querySelector(".state_dd"); //Validation var isEmailValid = validateEmail(email, true); var isFirstNameValid = validateName(firstName, true); var isLastNameValid = validateName(lastName, true); var isCountryValid = validateCountry(country, true); var isStateValid = $(state).hasClass("hidden") ? true : validateState(state, true); if (isEmailValid && isFirstNameValid && isLastNameValid && isCountryValid && isStateValid) { const dataJson = { "email": email.value, "firstName": firstName.value, "lastName": lastName.value, "country": country.value, "state": state.value ? state.value : '', }; return dataJson; } else return {}; } catch (e) { console.error(e); } } function validateEmail(email, isSetError) { //Email Validation: required and valid format var emailFormatReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var isEmailFormatValid = emailFormatReg.test(String(email.value).toLowerCase()); if (email.value != "" && isEmailFormatValid) { //remove error if valid var error = email.nextElementSibling; if (error != null && error.classList.contains('error')) { error.remove(); $(email).parents('.form-element').removeClass('error'); } return true; } else { //check if error already exist var error = email.nextElementSibling; if (error == null || error == undefined) { //append error setError(email, isSetError); } return false; } } function validateName(name, isSetError) { //Name Validation: required and can only contain alpha chars var strRegex = new RegExp(/^[A-Za-z\'\-]+(?:\s+[IVXLCDM]+)?$/i); var isNameValid = strRegex.test(String(name.value).toLowerCase()); if (name.value != "" && isNameValid) { //remove error if valid var error = name.nextElementSibling; if (error != null && error.classList.contains('error')) { error.remove(); $(name).parents('.form-element').removeClass('error'); } return true; } else { //check if error already exist var error = name.nextElementSibling; if (error == null || error == undefined) { //append error setError(name, isSetError); } return false; } } function validateCountry(country, isSetError) { //Country Validation: required if (country.value != "") { //remove error if valid var countryParent = $(country).parent(); var error = countryParent.next(); if (error != null && $(error).hasClass('error')) { $(error).remove(); $(country).parents('.form-element').removeClass('error'); $(country).siblings('.chosen-container').removeClass('error'); } return true; } else { //check if error already exist var countryParent = $(country).parent(); var error = countryParent.next(); if ((error == null || error == undefined || error.length == 0) && isSetError) { //append error const errorText = country.dataset.error; const error = document.createElement('span'); error.classList.add('error'); error.innerHTML = errorText; countryParent.after(error); $(country).parents('.form-element').addClass('error'); $(country).siblings('.chosen-container').addClass('error'); } return false; } } function validateState(state, isSetError) { //state Validation: required if (state.value != "") { //remove error if valid var stateParent = $(state).parent(); var error = stateParent.next(); if (error != null && $(error).hasClass('error')) { $(error).remove(); $(state).parents('.form-element').removeClass('error'); $(state).siblings('.chosen-container').removeClass('error'); } return true; } else { //check if error already exist var stateParent = $(state).parent(); var error = stateParent.next(); if ((error == null || error == undefined || error.length == 0) && isSetError) { //append error const errorText = state.dataset.error; const error = document.createElement('span'); error.classList.add('error'); error.innerHTML = errorText; stateParent.after(error); $(state).parents('.form-element').addClass('error'); $(state).siblings('.chosen-container').addClass('error'); } return false; } } function submitEnrollment(userData) { const response = fetch("/EnrollmentPage/ExternalEnroll", { method: "POST", headers: { 'Content-type': 'application/json', 'RequestVerificationToken': $('[name="__RequestVerificationToken"]').val() }, body: JSON.stringify(userData), }).then(function (response) { var form = $('#woh-enrollmentForm') const $alert = $(form).siblings('.form-alert'); $alert.removeClass('success error').text(''); if (response.ok) { response.json().then(function (data) { // Use this to parse error msgs in response json if need it if (data.Errors) $alert.addClass('error').text(data.Errors[0].Description); else { var urlObject = new URL(document.location.href); var params = urlObject.searchParams; var returnURL = params.get("returnURL"); var dataRedirectUriContainer = $(".hyattMenuHeaderSigninJoin").parent("div"); var isPopupEnabled = window.is_popup; if (isPopupEnabled === null || isPopupEnabled === undefined || !isPopupEnabled) { if (!(returnURL === null || returnURL === undefined) && returnURL != "") window.location.href = returnURL; else window.location.reload(); } else { window.opener.focus(); window.close(); window.opener.location.reload(); //signinBtn.focus(); } return data; } }); } else { $alert.addClass('error').text($alert.data('error')); } }) .catch(function (err) { // There was an error console.warn("Something went wrong.", err); }); return response; } function popupA11y(element) { element.setAttribute("aria-haspopup", "true"); } function loadStylesResources() { var head = document.getElementsByTagName('HEAD')[0]; // Create new link Element //var link = document.createElement('link'); //// set the attributes for link element //link.rel = 'stylesheet'; //link.type = 'text/css'; //link.href = '/modules/Trisept.Epi.Addons.WOH/ClientResources/styles/styles.css'; //// Append link element to HTML head //head.appendChild(link); } async function loadScriptEnrollmentForm() { var footer = document.querySelectorAll('FOOTER')[0]; var footerScript = footer.querySelectorAll("[href*=enrollment-form]"); if (footerScript == null || !footerScript.length) { await import('/modules/Trisept.Epi.Addons.WOH/ClientResources/Scripts/enrollment-form.js'); } } }());